import { getData, service } from '@vimi/utils-api'
import { addressCount, addressComplement } from '@vimi/utils-tool'

// 合并相同请求
const cacheTreeRequest = {}

export const getAddressNextValue = (address = '') => {
  const cutAddress = address.replace(/0+$/, (w, i) => Array(addressComplement[i] + 1).join('0'))
  return `${Number.parseInt(cutAddress) + 1}`.padEnd(addressCount, '0')
}

export async function getAddressAuth(address = '', level = 0, config) {
  const nextLevel = level + 1
  const params = {
    'region_lever.eq': nextLevel,
    fields: 'id,geo_name,region_lever',
    isBIQuery: 1,
  }

  if (address) {
    params['id.gt'] = address
    params['id.lt'] = getAddressNextValue(address)
  }

  const res = await getData('industrial_db', 'geo_codings', params, {}, config)
  return (res.data || []).map(item => ({
    id: item.id,
    geoName: item.geo_name,
    regionLever: item.region_lever,
  }))
}

export async function getAddress(address = '', config) {
  const key = address || 'province'

  let cache = cacheTreeRequest[key]
  if (cache && cache.loading) {
    return new Promise((resolve, reject) => {
      cache.queue.push({ resolve, reject })
    })
  }
  cache = cacheTreeRequest[key] = { loading: true, queue: [] }

  return service
    .get(`/industrial/geo/tree?addressCode=${address}`, config)
    .then(res => {
      const data = res.data || []
      cache.loading = false
      cache.queue.forEach(p => p.resolve(data))
      cache.queue = []

      return data
    })
    .catch(err => {
      cache.loading = false
      cache.queue.forEach(p => p.reject(err))
      cache.queue = []

      throw new Error(err)
    })
}
